<template>
  <div>
    <a-modal :title="'系列编辑'" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel1">
      <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="*系列标题">
          <a-input v-model="form.title" />
        </a-form-model-item>
        <a-form-model-item label="*系列描述">
          <a-input v-model="form.detail" />
        </a-form-model-item>

        <a-form-model-item label="*发布平台">
          <a-select v-model="form.publishPlatform">
              <a-select-option value="0">宏绮舍/一品布衣</a-select-option>
              <a-select-option value="1">深海漫故事</a-select-option>
          </a-select>     
        </a-form-model-item>
        <a-form-model-item label="外部书单ID">
          <a-input v-model="form.extBookId" />
        </a-form-model-item>
        <a-form-model-item label="*封面图">

          <a-upload :data="imgData" :file-list="fileList" list-type="picture" action="https://up-z2.qiniup.com/"
            @change="handleChange" @preview="previewFile">
            <a-button> <a-icon type="upload" /> 上传 </a-button>
          </a-upload>


        </a-form-model-item>
        <a-form-model-item label="打赏标题">
          <a-input v-model="form.RewardTit" />
        </a-form-model-item>
        <a-form-model-item label="打赏文案">
          <a-input v-model="form.RewardTxt" />
        </a-form-model-item>
        <a-form-model-item label="开始集数">
          <a-input v-model="form.startChapter" />
        </a-form-model-item>

        <a-form-model-item label="宣传视频">
          <a-upload :remove="handleRemove" :before-upload="beforeUpload" :file-list="fileVideoList">
            <a-button>
              上传
            </a-button>
          </a-upload>
          <a-progress v-if="fileVideoList.length > 0" :percent="percent" type="line" />
        </a-form-model-item>

      </a-form-model>
    </a-modal>
  </div>
</template>
<script>

import axios from 'axios'
import { addSeries, modifySeries, bossList, seriesList, groupList, uploadVideo } from "../../http/api"
export default {
  name: "userEdit",
  data () {
    return {
      visible: this.flag,
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      typeOptions: [],
      form: {
        _id: '',
        indexImg: '',
        detail: '',
        title: '',
        RewardTit: '',
        RewardTxt: '',
        startChapter: '',
        publishPlatform: '0',
        extBookId: '',
        videoUrl: '',
        FileId: '',
      },
      shopType: '',
      previewVisible: false,
      previewImage: '',
      fileList: [],
      fileVideoList: [],
      imgData: {},


      editType: 1, //1是新增 2是编辑

      bList: [],
      sList: [],
      gList: [],

      userInfo: {},//用户列表
      percent: 0,//视频上传进度,
    }
  },
  props: ["flag", "list"],
  created () {
    // console.log(this.list)
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (this.list._id) {
      this.form = {
        _id: this.list._id,
        indexImg: this.list.indexImg,
        detail: this.list.detail,
        title: this.list.title,
        RewardTit: this.list.RewardTit,
        RewardTxt: this.list.RewardTxt,
        startChapter: this.list.startChapter,
        publishPlatform:this.list.publishPlatform,
        extBookId: this.list.extBookId,
        videoUrl: this.list.videoUrl,
        FileId: this.list.FileId ? this.list.FileId : '',
      }

      this.fileList = [{
        uid: -1,
        name: 'image.png',
        status: 'done',
        url: this.list.indexImg,
      }]

      this.fileVideoList = [{
        uid: -2,
        name: this.list.videoUrl,
        status: 'done',
        url: this.list.videoUrl,
      }]

      this.editType = 2
    } else {
      this.editType = 1
    }
    this.imgData.token = this.list.imgToken
    // this.shopType = this.$store.state.user.shopId
    // if (this.shopType == '000') {
    //   this.bossList(1, this.$store.state.user.shopId)
    // }
    // this.groupList(1, this.$store.state.user.shopId)
  },
  methods: {
    handleChange (info) {
      let fileList = [...info.fileList]

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-2)

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url
        }
        return file
      })

      this.fileList = fileList
    },

    beforeUpload (videofile) {
      this.fileVideoList = [...this.fileVideoList,videofile]
      this.UploadVideo()
      return false
    },

    handleRemove (videofile) {
      const index = this.fileVideoList.indexOf(videofile)
      const newFileList = this.fileVideoList.slice()
      newFileList.splice(index, 1)
      this.fileVideoList = newFileList
    },

    //上传视频
    async UploadVideo () {
      let that = this
      this.spinning = true
      const tcVod = new TcVod.default({
        getSignature: await that.getSignature() // 前文中所述的获取上传签名的函数
      })
      const uploader = tcVod.upload({
        mediaFile: that.fileVideoList[0], // 媒体文件（视频或音频或图片），类型为 File
      })
      uploader.on('media_progress', function (info) {
        console.log(info.percent) // 进度
        that.percent = Number((Number(info.percent) * 100).toFixed(0))
        console.log(that.percent)
      })
      uploader.done().then(function (doneResult) {
        console.log('视频上传完成=====')
        console.log(doneResult)
        that.spinning = false
        that.videoUrl = doneResult.video.url
        that.FileId = doneResult.fileId

      })
    },

    getSignature () {
      let url = 'https://text-2g54vgfvcc0aee2b-1327065262.ap-shanghai.app.tcloudbase.com/TcbRouterAu'
      return function () {
        return axios.post(url, {
          "$url": "getYunToken",
        }).then(function (response) {
          console.log(response)
          return response.data.signature // 确保返回的是签名值
        })
      }
    },

    //商品图片
    imgCancel () {
      this.previewVisible = false
    },

    //预览图片
    previewFile (file) {
      console.log('Your upload file:', file)

    },

    //确认
    handleOk (e) {

      console.log(this.fileList)
      console.log(this.form)
      //判断数据完整性
      if (this.form.title == '') {
        this.$tishi("warning", '请输入系列标题')
        return
      }
      if (this.form.detail == '') {
        this.$tishi("warning", '请输入系列描述')
        return
      }
      if (this.form.publishPlatform == '1') {
        if(!this.form.extBookId){
          this.$tishi("warning", '请输入外部书单Id，如不清楚，请联系运营同学')
          return
        } else if(this.form.extBookId == ''){
          this.$tishi("warning", '请输入外部书单Id，如不清楚，请联系运营同学')
          return
        }
       
      }
      if (this.fileList.length == 0) {
        this.$tishi("warning", '请上传封面图')
        return
      }

      this.confirmLoading = true
      console.log(this.editType)
      if (this.editType == 2) {
        //修改数据
        this.modifySeries()
      } else {
        //新增数据
        this.addSeries()
      }
    },
    //点击取消 关闭弹框赋值
    handleCancel1 (e) {
      console.log("Clicked cancel button")
      this.visible = false
      this.$emit("func", this.visible)
    },
    //点击确定 关闭弹框赋值
    closefz () {
      this.visible = false
      this.confirmLoading = false
      this.$emit("func", this.visible)


    },
    async addSeries () {
      const parameter = {
        "$url": "addSeries",
        "title": this.form.title,
        "detail": this.form.detail,
        "indexImg": 'https://animationvideo.syhqcm.fun/' + this.fileList[0].response.key,
        "author": this.userInfo.name,
        "authorID": this.userInfo._id,
        "RewardTit": this.form.RewardTit,
        "RewardTxt": this.form.RewardTxt,
        "startChapter": this.form.startChapter,
        "publishPlatform": this.form.publishPlatform,
        "extBookId": this.form.extBookId,
        "videoUrl": this.videoUrl,
        "FileId": this.FileId,
      }
      var res = await addSeries(parameter)
      console.log('新增系列', res)
      if (res.code == 200) {
        this.$tishi("success", res.msg)
        this.closefz()

      } else {
        this.$tishi("warning", res.msg)
        this.confirmLoading = false
      }
    },
    async modifySeries () {
      //判断是否修改了图片
      let indexImg = ''
      if (this.fileList[0].url) {
        indexImg = this.fileList[0].url
      } else {
        indexImg = 'https://animationvideo.syhqcm.fun/' + this.fileList[0].response.key
      }

      //判断是否修改了视频
      let videoUrl = ''
      let FileId = ''
      console.log("aaaaaa");
      console.log(this.fileVideoList[0])
      if (this.fileVideoList[0]){
        if (this.fileVideoList[0].url) {
          videoUrl = this.fileVideoList[0].url
          FileId = this.form.FileId
        } else {
          videoUrl = this.videoUrl
          FileId = this.FileId
        }
      }
      
      const parameter = {
        "$url": "modifySeries",
        "title": this.form.title,
        "detail": this.form.detail,
        "indexImg": indexImg,
        "_id": this.form._id,
        "RewardTit": this.form.RewardTit,
        "RewardTxt": this.form.RewardTxt,
        "startChapter": this.form.startChapter,
        "publishPlatform": this.form.publishPlatform,
        "extBookId": this.form.extBookId,
        "videoUrl": videoUrl,
        "FileId": FileId,
      }
      var res = await modifySeries(parameter)
      console.log('修改系列', res)
      if (res.code == 200) {
        this.$tishi("success", res.msg)
        this.closefz()

      } else {
        this.$tishi("warning", res.msg)
        this.confirmLoading = false
      }
    },

  },
}
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>